<template>
  <div class="dashboard-container">
    <div class="welcome-section">
      <h2>欢迎使用 DBCompareX</h2>
      <p>数据库比较和同步工具</p>
    </div>
    
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-card">
              <div class="stat-icon">
                <el-icon :size="40" class="database-icon"><Setting /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statisticsData.dbCount }}</div>
                <div class="stat-label">数据库配置</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-card">
              <div class="stat-icon">
                <el-icon :size="40" class="task-icon"><Connection /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statisticsData.taskCount }}</div>
                <div class="stat-label">同步任务</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-card">
              <div class="stat-icon">
                <el-icon :size="40" class="running-icon"><Loading /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statisticsData.runningCount }}</div>
                <div class="stat-label">运行中任务</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-card">
              <div class="stat-icon">
                <el-icon :size="40" class="log-icon"><Document /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statisticsData.logCount }}</div>
                <div class="stat-label">执行日志</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <div class="dashboard-content">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>任务执行统计</span>
              </div>
            </template>
            <div id="task-chart" style="width: 100%; height: 350px;"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="recent-logs" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>最近执行日志</span>
                <el-button type="primary" text @click="viewAllLogs">查看全部</el-button>
              </div>
            </template>
            <div v-if="recentLogs.length > 0">
              <div v-for="log in recentLogs" :key="log.id" class="log-item">
                <div class="log-title">
                  <span>{{ log.taskName }}</span>
                  <el-tag :type="log.status === 'success' ? 'success' : (log.status === 'failed' ? 'danger' : 'warning')" size="small">
                    {{ statusMap[log.status] }}
                  </el-tag>
                </div>
                <div class="log-time">{{ formatDate(log.createTime) }}</div>
              </div>
            </div>
            <div v-else class="no-data">
              暂无执行日志
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <div class="quick-actions">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span>快捷功能</span>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="action-item" @click="navigateTo('/db-config')">
              <el-button type="primary" circle>
                <el-icon><Setting /></el-icon>
              </el-button>
              <div class="action-text">数据库配置</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="action-item" @click="navigateTo('/data-sync')">
              <el-button type="success" circle>
                <el-icon><RefreshRight /></el-icon>
              </el-button>
              <div class="action-text">创建同步任务</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="action-item" @click="navigateTo('/execution-log')">
              <el-button type="info" circle>
                <el-icon><Document /></el-icon>
              </el-button>
              <div class="action-text">查看执行日志</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="action-item" @click="refreshDashboard">
              <el-button type="warning" circle>
                <el-icon><RefreshLeft /></el-icon>
              </el-button>
              <div class="action-text">刷新面板</div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import { get } from '@/utils/request';
import { Setting, Connection, Loading, Document, RefreshRight, RefreshLeft } from '@element-plus/icons-vue';
import dayjs from 'dayjs';

const router = useRouter();

// 状态映射
const statusMap = {
  'success': '成功',
  'failed': '失败',
  'running': '执行中',
  'pending': '等待中'
};

// 统计数据
const statisticsData = reactive({
  dbCount: 0,
  taskCount: 0,
  runningCount: 0,
  logCount: 0
});

// 最近日志
const recentLogs = ref<any[]>([]);

// 初始化图表
const initTaskChart = (data: any) => {
  const chartDom = document.getElementById('task-chart');
  if (!chartDom) return;
  
  const myChart = echarts.init(chartDom);
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['成功', '失败']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '成功',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: data.success
      },
      {
        name: '失败',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: data.failed
      }
    ]
  };
  
  myChart.setOption(option);
  
  // 窗口大小改变时，重新调整图表大小
  window.addEventListener('resize', () => {
    myChart.resize();
  });
};

// 获取仪表盘数据
const fetchDashboardData = async () => {
  try {
    // 这里调用后端API获取数据，暂时使用模拟数据
    // const response = await get('/api/dashboard/statistics');
    
    // 模拟数据
    statisticsData.dbCount = 12;
    statisticsData.taskCount = 25;
    statisticsData.runningCount = 3;
    statisticsData.logCount = 158;
    
    // 图表数据
    const chartData = {
      dates: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      success: [10, 12, 15, 8, 14, 9, 11],
      failed: [3, 1, 2, 4, 2, 1, 2]
    };
    
    // 最近日志
    recentLogs.value = [
      { id: 1, taskName: '商品数据同步任务', status: 'success', createTime: '2023-05-21 10:35:22' },
      { id: 2, taskName: '用户数据比对', status: 'failed', createTime: '2023-05-21 09:15:46' },
      { id: 3, taskName: '订单数据同步', status: 'success', createTime: '2023-05-20 22:01:33' },
      { id: 4, taskName: '库存数据同步', status: 'running', createTime: '2023-05-20 21:42:17' },
      { id: 5, taskName: '供应商数据比对', status: 'success', createTime: '2023-05-20 18:30:05' }
    ];
    
    // 初始化图表
    initTaskChart(chartData);
  } catch (error) {
    console.error('获取仪表盘数据失败:', error);
  }
};

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

// 查看所有日志
const viewAllLogs = () => {
  router.push('/data-sync/log');
};

// 导航到指定页面
const navigateTo = (path: string) => {
  // 根据传入的路径映射到正确的子路由
  if (path === '/db-config') {
    router.push('/data-sync/db-config');
  } else if (path === '/data-sync') {
    router.push('/data-sync/task');
  } else if (path === '/execution-log') {
    router.push('/data-sync/log');
  } else {
    router.push(path);
  }
};

// 刷新仪表盘
const refreshDashboard = () => {
  fetchDashboardData();
};

// 生命周期钩子
onMounted(() => {
  fetchDashboardData();
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  
  .welcome-section {
    text-align: center;
    margin-bottom: 30px;
    
    h2 {
      font-size: 28px;
      font-weight: 600;
      color: var(--primary-color);
      margin-bottom: 8px;
    }
    
    p {
      font-size: 16px;
      color: var(--text-color-secondary);
    }
  }
  
  .stats-cards {
    margin-bottom: 30px;
    
    .stat-card {
      display: flex;
      align-items: center;
      
      .stat-icon {
        margin-right: 15px;
        
        .database-icon {
          color: #409eff;
        }
        
        .task-icon {
          color: #67c23a;
        }
        
        .running-icon {
          color: #e6a23c;
        }
        
        .log-icon {
          color: #909399;
        }
      }
      
      .stat-info {
        .stat-value {
          font-size: 24px;
          font-weight: 600;
          line-height: 1.2;
        }
        
        .stat-label {
          font-size: 14px;
          color: var(--text-color-secondary);
        }
      }
    }
  }
  
  .dashboard-content {
    margin-bottom: 30px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
    }
    
    .recent-logs {
      .log-item {
        padding: 10px 0;
        border-bottom: 1px solid var(--border-color-lighter);
        
        &:last-child {
          border-bottom: none;
        }
        
        .log-title {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 5px;
          font-size: 14px;
        }
        
        .log-time {
          font-size: 12px;
          color: var(--text-color-secondary);
        }
      }
      
      .no-data {
        text-align: center;
        padding: 30px 0;
        color: var(--text-color-secondary);
        font-size: 14px;
      }
    }
  }
  
  .quick-actions {
    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      cursor: pointer;
      transition: all 0.3s;
      padding: 15px 0;
      
      &:hover {
        transform: translateY(-5px);
      }
      
      .action-text {
        margin-top: 10px;
        font-size: 14px;
      }
    }
  }
}
</style>